package com.zy.openchat.util;

import android.os.Bundle;

import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.LinkedHashMap;

public abstract class AbsSpeechRecognizerListener implements RecognizerListener {
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<>();

    @Override
    public void onVolumeChanged(int volume, byte[] data) {
        showTip("当前正在说话，音量大小 = " + volume + " 返回音频数据 = " + data.length);
    }

    @Override
    public void onBeginOfSpeech() {
        showTip("开始说话");
    }

    @Override
    public void onEndOfSpeech() {
        showTip("结束说话");
    }

    @Override
    public void onResult(RecognizerResult results, boolean b) {
        String text = parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        onResult(resultBuffer.toString());
    }

    public abstract void onResult(String text);

    public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }

    @Override
    public void onError(SpeechError speechError) {
        showTip(speechError.getPlainDescription(true));
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {
        showTip("onEvent");
    }

    private void showTip(final String str) {
//        ToastUtils.showShort(str);
    }
}
